import axios from 'axios'
import router from '../router'

// 创建axios实例
const service = axios.create({
    baseURL: '/api/', // api的base_url
    timeout: 15000*100, // 请求超时时间
    headers: {
        "Pragma": "no-cache",
        "Cache-Control": "must-revalidate",
        "Cache-Control": "no-cache" ,
        "Cache-Control": "no-store",
    }
})
const notSetAuthHeaderUrls = [
    './sys/token',
    './uua/login',
    './uua/mobile/login',
    './sys/authUsers/emailCode',
    './sys/authUsers/smsCode',
    './sys/authUsers/mobile/smsCode',
    './sys/authUsers/resetPwd',
    './sys/captcha',
    './uua/sso/login',
    './uum/authUsers/emailCode',
    './uum/authUsers/resetPassword',
    '/uua/getGoogleAuthenticatorCode',
    './uua/jhoauthsso/login',
]
const base64= [
     "./uum",
    "./sys",
    "./device",
    "./drap",
    "./train",
    "./data",
    "./pszczx",
    "./secure",
    "./register",
    "./file-service",
     "./dp-service",
    "./realTimeDynamic"
]

const needDownloadUrl=[
    "/uum/secretUpload/download",
    "/uum/deviceSystemLog/download",
    "/uum/authUsers/download",
    "/uum/authOrgs/download",
    "/drap/task/getTaskImagesUrl1",
    "/drap/template/templateInfos/download/template",
    "/drap/task/taskAnswers/preservationAndExportReport",
    "/dp-service/fj/fjDataSecurityOrders/downloadServiceOrderFile",
    "/dp-service/fj/fjDataSecurityOrders/downloadDemanderOrderFile",
    "/dp-service/fj/fjDataSecurityOrders/downloadPlatformOrderFile",
    "/dp-service/fj/fjDataSecurityOrders/downloadProveFile",
    "/dp-service/fj/fjDataSecurityOrders/downloadServiceFile",
    // "/uum/sysAllAuditLogs/backups"
    "/train/trainExamQuestions/downloadModel",
    "/data/dataSecurityKnowledges/downloadZip",
    "/fj/fjProductApplyOrderArbitrations/downloadContractFile",
    "/fj/fjUserApplications/getImageBase64",
    "/fj/fjProductApplyOrderContracts/downloadContractFile",
    "/fj/fjProductApplyOrderContracts/downloadContractDocFile",
    "/fj/fjProductApplyOrderContracts/downloadContractPdfFile",
    "/data/export/getProductTotalXls",
    "/data/export/getOrderTotalXls",
    "/data/export/getOrderProductTotalXls",
    "/data/export/getOrderTotalByTimeXls",
    "/data/export/getApplicationTotalByTimeXls",
    "/data/export/getOrderActiveSceneXls",
    "/data/export/getApplicationActiveSceneXls",
    "/data/export/getOrderTrendLineChartsXls",
    "/data/export/getProductTrendLineChartsXls",
    "/data/export/getAmountTrendLineChartsXls",
    "/data/export/getStatementsXls",
    "/dp-service/fj/serviceEnterpriseStatistics/downloadReport",
    "/dp-service/fj/dataSecurityKnowledges/downloadZip", // 内容管理附件下载
    "/dp-service/fj/fjUserApplications/getSettleFile"
]

// request拦截器
service.interceptors.request.use(config => {

    // if (needSetAuthHead(config.url)) {
    //     // config.headers['Auth'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    //     // config.headers['Authorization'] = 'Bearer ' + getToken()
    //     config.headers['Authorization'] = 'Bearer ' + getToken()
    // }
    if(needBase64(config.url)){
        if(config.method=="post"||config.method=="put"){
            config.headers.post["Content-Type"] = "application/json;charset=UTF-8";
            config.headers.put["Content-Type"]="application/json;charset=UTF-8";
            config.data=Base64.encode(JSON.stringify(config.data));
        }
    }
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非20000是抛错 可结合自己业务进行修改
         */
        if(needBase64(response.config.url)){
            if(!needDownload(response.config.url)){
                response.data=JSON.parse(Base64.decode(response.data));
            }
        }
        if (response['headers']['content-disposition']) {
            const data = response.data;
            var fileName = response['headers']['content-disposition'].split(";")[1].split("filename=")[1];
            var index = fileName.lastIndexOf("\"");
            if (index == fileName.length - 1) {
                var start = 0;
                if (fileName.indexOf("\"") == 0) {
                    start = 1;
                }
                fileName = fileName.substring(start, index);
            }
            return {
                data,
                fileName
            }
        }
        if (response['headers']['captcha-uid']) {
            return response;
        }
        const res = response.data;
        if (res['access_token'] || !res.status) {
            return response.data;
        }
        if (res.status != 200) {
            if(res.status == 'success'){
                return response.data
            }
            if (res.status == 401) {
                router.push({
                    path: '/login',
                })
            } else {
                // if(error.data.errMsg=='551'){
                //     msg("您的密码已过期，请重新修改密码");
                // }else if(error.data.errMsg=='550'){
                //     msg("您的密码已过期，请尽快修改密码");
                // }
                // msg(res.msg);
            }
            return Promise.reject(res)
        } else {
            return response.data
        }
    },
    error => {
        if (error && error.response) {
            if (error.response.status == 401) {
                // removeToken();
                router.push({
                    path: '/login',
                })
                //location.href = "https://rz.jhsec.com.cn/oauth/authorize?client_id=sjkjfw&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A8080%2F%23%2FoauthSSO";
                // location.reload()
            } else if (error.response.status == 403) {
                alert('无权访问')
            } else if (error.response.status == 500) {
                // this.$message.error('系统繁忙,请稍后再试')
            }
        }
        console.log('err' + error) // for debug
        // store.dispatch('user/LOGOUT').then(() => {
        //   //location.reload()// 为了重新实例化vue-router对象 避免bug
        // })
        // Message({
        //   message: error.message,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        return Promise.reject(error)
    }
)


const needSetAuthHead = (url) => {
    if (url.indexOf('uua/jhoauthsso/login') > 0){
        return false
    }
    return notSetAuthHeaderUrls.indexOf(url) == -1;
}
const needDownload = (repUrl) =>{
    var needUploadFlag=false;
    needDownloadUrl.forEach(url =>{
        if(repUrl.indexOf(url)!=-1){
            needUploadFlag=true;
        }
    })
    return needUploadFlag;
}

// const needBase64 = (url) => {
//     return url.indexOf("/sys/")>=0||url.indexOf("/uum/")>=0||url.indexOf("/device/")>=0;
// }

const needBase64 = (reqUrl) => {
    var needBaseFlag=false;
    if(process.env.VUE_APP_AJAX_ENCYPT=='true'){
        base64.forEach(url =>{
            if(reqUrl.indexOf(url)!=-1  && reqUrl.indexOf("upload")==-1){
                needBaseFlag=true;
            }
        });
    }
    return needBaseFlag;
}

/* eslint-disable no-proto */
service.__proto__ = axios
/* eslint-enable */

export default service
